<?php

namespace App\Http\Controllers\Api\v2;

use App\Http\Controllers\ApiController;
use App\Models\Collect;
use App\Models\Item;
use App\Models\PostItem;
use App\Models\Shop;

class CollectController extends ApiController
{
    public function add()
    {
        $dataid = $this->request->input('dataid');
        $datatype = $this->request->input('datatype');

        $collect = Collect::where(['uid'=>$this->uid, 'dataid'=>$dataid, 'datatype'=>$datatype]);
        if (!$collect->exists()){
            if ($datatype == 'article') {
                $article = PostItem::find($dataid);
                if ($article) {
                    Collect::insert([
                        'uid'=>$this->uid,
                        'dataid'=>$dataid,
                        'datatype'=>$datatype,
                        'title'=>$article->title,
                        'image'=>$article->image,
                        'created_at'=>time()
                    ]);
                }
            }

            if ($datatype === 'item') {
                $item = Item::find($dataid);
                if ($item) {
                    Collect::insert([
                        'uid'=>$this->uid,
                        'dataid'=>$dataid,
                        'datatype'=>$datatype,
                        'title'=>$item->title,
                        'image'=>$item->thumb,
                        'created_at'=>time()
                    ]);
                }
            }

            if ($datatype == 'shop') {
                $shop = Shop::find($dataid);
                if ($shop) {
                    Collect::insert([
                        'uid'=>$this->uid,
                        'dataid'=>$dataid,
                        'datatype'=>$datatype,
                        'title'=>$shop->shop_name,
                        'image'=>$shop->logo,
                        'created_at'=>time()
                    ]);
                }
            }
        }

        return ajaxReturn();
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function getItemList()
    {
        $offset = $this->request->input('offset');
        $count  = $this->request->input('count');
        $offset = $offset ? $offset : 0;
        $count  = $count ? $count : 20;

        $datatype = $this->request->input('datatype');
        !$datatype && $datatype = 'item';

        $items = Collect::where('uid', $this->uid)->where('datatype', $datatype)
            ->offset($offset)->limit($count)->orderByDesc('id')->get()->map(function ($item){
                 $item->image = image_url($item->image);
                 $item->created_at = @date('Y-m-d H:i:s', $item->created_at);
                 return $item;
            });

        return ajaxReturn(['items'=>$items]);
    }
}
